﻿// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Data;
using System.Data.Common;
using JetBrains.Annotations;
using Oracle.ManagedDataAccess.Client;

namespace SnapObjects.Data.Oracle
{
    public abstract class OracleTypeMapping : TypeMapping
    {
        public OracleTypeMapping(
            [NotNull] string dbTypeName,
            [NotNull] Type clrType,
            [CanBeNull] DbType? dbType = null,
            bool unicode = false,
            int? size = 30) : base(dbTypeName, clrType, dbType, unicode, size)
        { 
        }

        public override DbParameter CreateParameter([NotNull] DbCommand command, [NotNull] IAdoDbParameter adoDbParameter)
        {
            var parameter = base.CreateParameter(command, adoDbParameter);

            if (command.CommandType == CommandType.StoredProcedure)
            {
                if (!String.IsNullOrWhiteSpace(parameter.ParameterName) && 
                    parameter.ParameterName.StartsWith(OracleSqlGenerationHelper.PARAMETERIDENTIFIER + ""))
                {
                    parameter.ParameterName = parameter.ParameterName.TrimStart(OracleSqlGenerationHelper.PARAMETERIDENTIFIER);
                }
            }

            return parameter;
        }

        protected override void ConfigureParameter([NotNull] DbParameter parameter, IAdoDbParameter adoDbParameter)
        {
            base.ConfigureParameter(parameter, adoDbParameter);

            if (adoDbParameter.ClrType != null && adoDbParameter.ClrType.IsArray)
            {
                ((OracleParameter)parameter).CollectionType = OracleCollectionType.PLSQLAssociativeArray;

                if (adoDbParameter.Direction == ParameterDirection.Output && 
                    adoDbParameter is AdoDbParameter param)
                {
                    ((OracleParameter)parameter).Size = param.Size;
                }
            }
        }
    }
}
